# @Author:黄景涛
# @Date: 2023/11/10
import openpyxl
from collections.abc import Iterable

"""excel相关的处理"""


class Excel:

    def __init__(self, file_path: str, sheet_header: tuple = None, sheet_name: str = None):
        self.file_path = file_path
        # 创建excel文件对象
        self.workbook = self.create_file()
        # 创建sheet页：若需要则创建，否则默认
        if sheet_name:
            self.sheet = self.workbook.create_sheet(sheet_name)
        else:
            self.sheet = self.workbook.active
        # 表头设置，如：('用例编号', '用例名称', '用例等级', '分组', '前置步骤', '测试步骤', '预期结果')
        self.sheet_header = sheet_header

    def create_file(self):
        workbook = openpyxl.Workbook()
        # workbook.save(self.file_path)
        return workbook

    def write_header(self):
        if not self.sheet_header:
            return
        self.sheet.append(self.sheet_header)

    def write_row(self, data: Iterable):
        """ 写入一行 """
        self.sheet.append(data)

    def write_col(self):
        """ 写入一列 """
        pass

    def read_excel(self):
        """ 读取excel数据 """
        pass

    def save(self):
        """保存excel（必须执行一下  --这里不能用__del__方法）"""
        self.workbook.save(self.file_path)


if __name__ == '__main__':
    e = Excel(r'../TEST.xlsx', sheet_header=('用例名称', '用例等级', '分组', '前置步骤', '测试步骤', '预期结果'))
    # 写入表头
    e.write_header()
    # 保存excel
    e.save()
